package com.zkj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkj.dto.SetmealDTO;
import com.zkj.dto.SetmealPageQueryDTO;
import com.zkj.entity.Setmeal;
import com.zkj.entity.SetmealDish;
import com.zkj.mapper.SetmealDishMapper;
import com.zkj.mapper.SetmealMapper;
import com.zkj.result.PageResult;
import com.zkj.result.Result;
import com.zkj.service.ISetmealDishService;
import com.zkj.service.ISetmealService;
import com.zkj.vo.DishItemVO;
import com.zkj.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author zkj
 * @since 2024-08-22
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Override
    public List<DishItemVO> getDishItemById(Long id) {

        return setmealMapper.getDishItemBySetmealId(id);
    }

    @Override
    public Result<Page<Setmeal>> pageQuery(Page<Setmeal> page, SetmealPageQueryDTO setmealPageQueryDTO) {

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        if(setmealPageQueryDTO.getName() != null){
            queryWrapper.like(Setmeal::getName,setmealPageQueryDTO.getName());
        }
        if(setmealPageQueryDTO.getCategoryId() != null){
            queryWrapper.eq(Setmeal::getCategoryId,setmealPageQueryDTO.getCategoryId());
        }
        if(setmealPageQueryDTO.getStatus() != null){
            queryWrapper.eq(Setmeal::getStatus,setmealPageQueryDTO.getStatus());
        }
        Page<Setmeal> setmealPage = setmealMapper.selectPage(page, queryWrapper);
        return Result.success(setmealPage);
    }

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDTO
     */
    @Transactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        //向套餐表插入数据
        setmealMapper.insert(setmeal);

        //获取生成的套餐id
        Long setmealId = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });

        //保存套餐和菜品的关联关系
        setmealDishMapper.insertBatch(setmealDishes);
    }



}
